<template>
  <view class="">
    <view class="base_choose">
      <view class="selectBtn">
        <button :class="{ active: chooseRoom}" @tap="chooseRoom = true;dateIndex= chooseDay ? -1 : 0;timeIndex=-1;roomIndex=-1;clearMoney();">按整室预定</button>
        <button :class="{ active: !chooseRoom}" @tap="chooseRoom = false;dateIndex= chooseDay ? -1 : 0;timeIndex=-1;roomIndex=-1;clearMoney();">按雅间预定</button>
      </view>
      <view class="selectBtn">
        <button :class="{ active: chooseDay}" @tap="chooseDay = true;dateIndex=-1;timeIndex=-1;roomIndex=-1;clearMoney();">按天选择</button>
        <button :class="{ active: !chooseDay}" @tap="chooseDay = false;dateIndex=0;timeIndex=-1;roomIndex=-1;clearMoney();">按时段选择</button>
      </view>
    </view>
    <view v-if="!chooseDay" style="background: #fff;padding: 10rpx 0 20rpx;">
      <view class="year_month">2024年10月</view>
      <scroll-view class="sroll_date" enable-flex scroll-x>
        <view class="dates_box">
          <view v-for='(item,index) in dateData' class="date_item" :class="dateIndex == index? 'on':''" @click="chooseDate(index)">
            <view class="week_name">{{item.week}}</view>
            <view class="date">{{item.date}}</view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="inner">
      <view v-if="!chooseRoom">
        <view class="block_item" v-for="(item,index) in rooms" v-if="item.room_time_price.length!==0">
          <view v-if="!chooseDay">
            <view class="block_title">{{item.name}}</view>
            <view class="time_block_choose">
              <view v-for="(time,time_index) in item.room_time_price" v-if='!time.is_day' :class="{'disabled': time.already_date.includes(dateData[dateIndex].date) , 'choose':timeIndex == time_index && index == roomIndex} " @click="changeTimeIndex(time_index,index)">
                {{ time.start_time.slice(0,time.start_time.length-3)}}-{{time.end_time.slice(0,time.end_time.length-3)}}
              </view>
            </view>
          </view>
          <view v-else>
            <view v-for="(time,time_index) in item.room_time_price" v-if='time.is_day'>
              <view class="block_title">{{item.name}}</view>
              <view class="date_block_choose">
                <view v-for='(date,date_index) in dateData' :class="{'disabled': time.already_date.includes(date.date) , 'choose':dateIndex == date_index && index == roomIndex} " @click="changeDateIndex(date_index,index,time_index)">
                  {{date.date}}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-else>
        <view class="block_item" v-if="item.name=='整间' && item.room_time_price.length!==0" v-for="(item,index) in rooms">
          <view v-if="!chooseDay">
            <view class="block_title">{{item.name}}</view>
            <view class="time_block_choose">
              <view v-for="(time,time_index) in item.room_time_price" v-if='!time.is_day' :class="{'disabled': time.already_date.includes(dateData[dateIndex].date) , 'choose':timeIndex == time_index && index == roomIndex} " @click="changeTimeIndex(time_index,index,dateIndex)">{{ time.start_time.slice(0,time.start_time.length-3)}}-{{time.end_time.slice(0,time.end_time.length-3)}}</view>
            </view>
          </view>
          <view v-else>
            <view v-for="(time,time_index) in item.room_time_price" v-if='time.is_day'>
              <view class="block_title">{{item.name}}</view>
              <view class="date_block_choose">
                <view v-for='(date,date_index) in dateData' :class="{'disabled': time.already_date.includes(date.date) , 'choose':dateIndex == date_index && index == roomIndex} " @click="changeDateIndex(date_index,index,time_index)">
                  {{date.date}}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <u-gap height="200"></u-gap>
    <view class="bottom">
      <view class="payType box" >
        <radio-group @change="payIndexChange" style="width: 100%;">
          <label class="uni-list-cell uni-list-cell-pd">
            <view>微信支付</view>
            <view>
              <radio value="0" :checked="payIndex == 0" disabled />
            </view>
          </label>
          <label class="uni-list-cell uni-list-cell-pd">
            <view>积分支付(余额：￥{{number}})</view>
            <view>
              <radio value="1"  :checked="payIndex == 1"/>
            </view>
          </label>
        </radio-group>
      </view>
      <view class="price_submit">
        <view class="price">
          <view class="totalPrice">总价：<view class="momey">￥{{money.total}}</view></view>
          <view class="inPrice">
            <view>押金：￥{{money.deposit}}</view>
            <view>使用金：￥{{money.price}}</view>
          </view>
        </view>
        <view class="submit" @click="submit()">提交订单</view>
      </view>
    </view>

  </view>
</template>
<script>
export default{
  data() {
    return {
      room_id: 0,
      chooseRoom: true,
      chooseDay: true,
      roomIndex:-1,  //选中房间下标
      dateIndex:-1, //选中日期下标
      timeIndex:-1,   //选中时间下标
      dateData: [],  // 十天日期
      rooms: null,
      currentMoth: null,
      money:{
        total:0,
        deposit:0,
        price:0
      },
      payIndex:1,
      number:0,
    }
  },
  onLoad: function(option){

    uni.showLoading({
      title: '加载中...'
    });

    this.room_id = option.id

    this.getDetail(option.id)
    // 获取今天的日期
    let currentDate = new Date();
    this.currentMoth = currentDate.getFullYear() + "年" + currentDate.getMonth() + "月"

    // 循环生成连续的十天日期
    for (let i = 0; i < 10; i++) {
      let year = currentDate.getFullYear();
      let month = currentDate.getMonth() + 1; // getMonth() 返回值是从 0 开始的，所以要加 1
      let day = currentDate.getDate();

      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      let week = days[currentDate.getDay()]
      // 格式化日期为 YYYY-MM-DD 的字符串
      let formattedDate = (month < 10 ? '0' + month : month) + '/' + (day < 10 ? '0' + day : day);

      // 将格式化后的日期字符串添加到 dateData 数组中
      this.dateData.push({date: formattedDate, week: week});

      // 将日期增加一天，以便生成下一天的日期
      currentDate.setDate(currentDate.getDate() + 1);
    }


  },
  methods: {
    clearMoney(){
      this.money={
        total:0,
        deposit:0,
        price:0
      }
    },
    chooseDate(index){
      this.dateIndex = index
      console.log(this.dateIndex)
    },
    changeDateIndex(date_index,index,time_index){
      this.dateIndex = date_index
      this.roomIndex = index
      this.timeIndex = time_index
      console.log(this.rooms[index].room_time_price[time_index])
      this.countMoney()
    },
    changeTimeIndex(time_index,index){
      this.timeIndex = time_index
      this.roomIndex = index
      console.log(this.rooms[index].room_time_price[time_index])
      this.countMoney()
    },
    change(e){
      console.log(e.detail.index)
    },
    getDetail(id){
      uni.$u.http.post('/getRoomDetail',{id}).then(res => {
        //设置当前房间名
        uni.setNavigationBarTitle({
          title: res.data.name
        })
        this.rooms = res.data.private_room
        console.log(res.data.private_room)
        this.rooms.forEach(item=>{
          item.room_time_price.forEach(time=>{
            if(time.already_date.length){
              time.already_date.forEach((alDate,index)=>{
                time.already_date[index] = alDate.start_time.slice(5,10).replace('-','/')
              })
            }
          })
        })
        uni.$u.http.post('getBalance').then(res => {
          this.number = res.data
          this.countMoney()
          uni.hideLoading();
        }).catch(error => {
          uni.showToast({
            title: '获取用户余额失败',
            icon: 'error',
            duration: 1000 // 提示框持续时间，单位为毫秒
          })
        })

      }).catch(error => {
        uni.showToast({
          title: '获取房间详情失败',
          icon: 'error',
          duration: 1000 // 提示框持续时间，单位为毫秒
        })
      })
    },
    getDayOfWeek(dateString) {
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const date = new Date(dateString);
      return days[date.getDay()];
    },
    getDate(dateString) {
      const date = new Date(dateString);
      let month = date.getMonth() + 1; // getMonth() 返回值是从 0 开始的，所以要加 1
      let day = date.getDate();
      return (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
    },
    //计算费用的函数
    countMoney(){
      if(this.roomIndex == -1){
        return;
      }else if(this.dateIndex == -1){
        return;
      }else if(this.timeIndex == -1){
        return;
      }
      this.money.deposit = Number(this.rooms[this.roomIndex].room_time_price[this.timeIndex].deposit)
      this.money.price =  Number(this.rooms[this.roomIndex].room_time_price[this.timeIndex].price)
      this.money.total = this.money.deposit+this.money.price
      console.log(this.money)
    },
    payIndexChange(evt){
      this.payIndex = Number(evt.detail.value)
    },
    submit(){
      if(this.roomIndex == -1){
        uni.showToast({
          title: '未选中具体房间',
          icon: 'error',
          duration: 1000 // 提示框持续时间，单位为毫秒
        })
        return;
      }else if(this.dateIndex == -1){
        uni.showToast({
          title: '未选中有效日期',
          icon: 'error',
          duration: 1000 // 提示框持续时间，单位为毫秒
        })
        return;
      }else if(this.timeIndex == -1){
        uni.showToast({
          title: '未选中有效时间段',
          icon: 'error',
          duration: 1000 // 提示框持续时间，单位为毫秒
        })
        return;
      }

      var form = {
        room_id:this.room_id,
        private_room_id:this.rooms[this.roomIndex].id,
        room_time_price_id:this.rooms[this.roomIndex].room_time_price[this.timeIndex].id,
        date:new Date().getFullYear()+'-'+this.dateData[this.dateIndex].date.replace('/','-'),  //2024-04-10
        is_wx_pay: this.payIndex==0 ? 1:0,
        is_balance_pay: this.payIndex==1 ?1:0
      }
      // console.log(form)

      uni.$u.http.post('bookingRoom',{
        ...form
      }).then(res => {
        console.log(res);
        if(res.code == 200){
          let order_no = res.data.order_no
          uni.showToast({
            title: '订单提交成功',
            icon: 'sucess',
            duration: 1000 ,// 提示框持续时间，单位为毫秒
            success: () => {
              setTimeout(() => {
                // 跳转至订单详情页
                uni.navigateTo({
                  url: `../selectOrder/index?order_no=${order_no}`
                })
              }, 1000)
            }
          })

        }else{
          uni.showToast({
            title: res.msg,
            icon: 'error',
            duration: 1000 // 提示框持续时间，单位为毫秒
          })
        }

        //如果支付失败就是201  带着201去到订单
      }).catch(error => {
        uni.showToast({
          title: '订单提交失败',
          icon: 'error',
          duration: 1000 // 提示框持续时间，单位为毫秒
        })
      })
    }
  }
}
</script>

<style lang="scss">
.base_choose{
  width: 100vw;
  padding: 20rpx 0;
}
.selectBtn {
  width: 100%;
  display: flex;
  justify-content:space-between;
}
.selectBtn:last-of-type{
  margin-top: 10rpx;
}
.selectBtn button {
  width: 45%;
  text-align: center;
  font-size: 24rpx;
  margin: 10rpx 20rpx 0 20rpx;
}
.selectBtn button:first-child{
  margin-right: 10rpx;
}
.selectBtn button:last-child{
  margin-left: 10rpx;
}
.active {
  background-color: #ccc; /* 设置按钮的点击后背景色 */
  color: #333; /* 设置按钮的点击后文字颜色 */
}
.year_month{
  font-weight: 600;
  font-size: 28rpx;
  color: #333;
  margin-top: 20rpx;
  margin-left: 20rpx;
}
.button-container {
  display: flex;
  flex-wrap: wrap;
}

.button-container button {
  width: calc(20% - 20rpx); /* 每行五个按钮，占据父容器的 20% 宽度，并留出一定间隙 */
  margin: 10rpx; /* 按钮之间的间隔 */
  padding: 4rpx 20rpx;
  background-color: white;;
}
.button-container button view{
  font-size: 24rpx;
  height: 44rpx;
  line-height: 40rpx;
  color: #a3a3a3;
  margin:0 auto;
}
.button-container button view:first-child{
  font-weight: bold;
  color:black;
}

.base_choose {
  width: 100vw;
}
.sroll_date{
  width: 100vw;
  height: 100rpx;
}
.dates_box{
  width: fit-content;
  display: flex;
  align-items: flex-end;
  margin-top: 10rpx;
}
.date_item{
  width:100rpx;
  height: 80rpx;
  text-align: center;
  font-weight: 500;
  background: #fff;
  margin-left: 10rpx;
  font-size: 24rpx;
  padding: 0 10rpx;
  white-space: nowrap;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3);
}
.date_item:first-of-type{
  margin-left: 20rpx;
}
.date_item.on{
  background:rgba(51, 153, 0, 0.1);
  border: 1px solid #339900;
}
.week_name{
  font-weight:600;
}
.date{
  font-size: 18rpx;
  margin-top: 6rpx;
}
.block_box{
  width: 100vw;
  height: calc(100vh - 200rpx);
  background:#fff;
  padding-bottom: calc(env(safe-area-inset-bottom));
}
.inner{
  width: 100%;
  height: fit-content;
}
.block_item{
  width: calc(100%-40rpx);
  margin: 0 20rpx;
  padding: 20rpx 0 0;
}
.block_title{
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #ccc;
  padding-bottom: 20rpx;
}
.time_block_choose,.date_block_choose{
  width: calc(100%-40rpx);
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0 0;
}
.time_block_choose view{
  width: 30%;
  height: 80rpx;
  border-radius: 20rpx;
  margin-right: 5%;
  background:#6699cc ;
  line-height: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #fff;
  margin-bottom: 20rpx;
}
.time_block_choose view:nth-child(3n),.date_block_choose view:nth-child(5n){
  margin-right: 0;
}
.time_block_choose view.choose{
  background:#663300;
}
.date_block_choose view{
  width: 18%;
  margin-right: 2.5%;
  margin-bottom: 20rpx;
  color: #fff;
  background:#6699cc;
  margin-left: 0 !important;
  padding: 0;
  height: 80rpx;
  line-height: 80rpx;
  font-weight: 500;
  font-size: 24rpx;
  white-space: nowrap;
  border-radius: 20rpx;
  text-align: center;
}
.date_block_choose view.choose{
  background: #CC9966;
}
.date_block_choose view:first-child{
  margin-left: 20rpx;
}
.disabled{
  background:#ccc !important;
  pointer-events: none !important;
}
.bottom{
  width: 100vw;
  position: fixed;
  padding-bottom: calc(env(safe-area-inset-bottom));
  bottom: 0;
  background: #fff;
  border-top: 2rpx solid #ccc;
}
.price_submit{
  display: flex;
  justify-content: space-between;
  width: 100vw;
  height: 100rpx;
  border-top: 2rpx solid #ccc;
}
.submit{
  width: 25%;
  text-align: center;
  height: 100rpx;
  line-height:100rpx ;
  background:blue;
  color: white;
  font-size: 28rpx;
}
.price{
  width: calc(100vw - 25%);
  height: 100rpx;
  display: flex;
  align-items: center;
  padding-left: 20rpx;
}
.totalPrice{
  width: fit-content;
  word-wrap: unset;
  color: #ccc;
  display: flex;
  align-items: baseline;
}
.momey{
  color: red;
  font-size: 40rpx !important;
}
.inPrice{
  margin-left: 10rpx;
  font-size: 24rpx !important;
}
.box{
  width: 100vw;
  padding: 10rpx 0;
  background: #fff;
}
.payType label{
  width: calc(100% - 40rpx);
  height: 100rpx;
  display: flex;
  margin: 0 20rpx;
  align-items: center;
  justify-content: space-between;
  border-bottom: 2rpx solid #ccc;
}
.payType label:last-child{
  border-bottom: none;
}
.withdrawalPopup-list {
  width: 100%;
  padding-bottom: 41rpx;

  .withdrawalPopup-list-item {
    width: 100%;
    height: 112rpx;
    border-radius: 55rpx;
    border: 2px solid #E3E3E3;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 0 28rpx;
    margin-bottom: 41rpx;

    .withdrawalPopup-list-item-l {
      display: flex;
      align-items: center;

      image {
        width: 70rpx;
        height: 70rpx;
        margin-right: 26rpx;
      }

      font-family: PingFang SC;
      font-weight: 400;
      font-size: 30rpx;
      color: #292929;
    }

    &>image {
      width: 42rpx;
      height: 42rpx;
    }
  }
}
</style>